<script setup lang="ts">
/**
 * @see {@link https://vuejs.org/api/sfc-script-setup.html#defineoptions}
 */
// 富文本
import Editor from "@/components/WangEditor/index.vue";
import {
  getListPage,
  getListAdd,
  getListEdit,
  getListDel,
  getRefreshAll
} from "@/api/config";

import { ListQuery, ListInfo, configForm } from "@/api/config/types";

const queryFormRef = ref(ElForm); // 查询表单
// 获取表单
const menuFormRef = ref(ElForm);

const loading = ref(false);
const total = ref(0);
const dialog = reactive<DialogOption>({
  visible: false,
});

const queryParams = reactive<ListQuery>({
  page: 1,
  ps: 10,
});

const userList = ref<ListInfo[]>();

// 表单提交数据
const formData = reactive<configForm>({
  id: '',
  code: '',
  name: '',
  input_type: 'text',
  val: '',
  ext: '',
  pid: 0,
  sort: 0,
  remark: '',
  checkbox: []
});

// 表单验证
const rules = reactive({
  code: [{ required: true, message: "请输入标题", trigger: "blur" }],
  name: [{ required: true, message: "选择状态", trigger: "blur" }],
  val: [{ required: true, message: "请输入内容", trigger: "blur" }],
});

const hanldeChangeRadio = (val: any) => {
  if (formData.input_type == 'text') {
    formData.ext = '';
  } else if (formData.input_type == 'radio') {
    formData.ext = [{ name: '', id: 1 }, { name: '', id: 2 }]
  } else if (formData.input_type == 'checkbox') {
    formData.ext = [{ name: '', id: 1 }, { name: '', id: 2 }]
  }
}

/**
 * 查询
 */
function handleQuery() {
  loading.value = true;
  getListPage(queryParams)
    .then(({ data }) => {
      userList.value = data.data;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.page = 1;
  handleQuery();
}

// 新增或者修改
const isEdit = ref(false);

// 打开弹窗
const openDialog = (postId?: number | string, data?: any) => {
  dialog.visible = true;
  if (postId) {
    isEdit.value = true;
    dialog.title = "修改配置";
    Object.assign(formData, data);
  } else {
    isEdit.value = false;
    dialog.title = "新增设置";
  }
}

// 确认提交
const submitForm = () => {

  menuFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      // formData.ext = JSON.stringify(formData.ext);
      formData.val = formData.val + '';
      if (formData.id) {
        getListEdit(formData).then((res: any) => {
          ElMessage.success(res.msg);
          closeDialog();
          handleQuery();
        })
      } else {
        getListAdd(formData).then((res: any) => {
          ElMessage.success(res.msg);
          closeDialog();
          handleQuery();
        })
      }
    }
  })
}

/** 删除菜单 */
function handleDelete(menuId: number) {
  ElMessageBox.confirm("确认删除该条的数吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    getListDel({ ids: [menuId] }).then(() => {
      ElMessage.success("删除成功");
      handleQuery();
    });
  }).catch(() => ElMessage.info("已取消删除"));
}

/** 关闭弹窗 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/** 重置表单 */
function resetForm() {
  menuFormRef.value.resetFields();
  menuFormRef.value.clearValidate();

  formData.id = '';
  formData.code = '';
  formData.name = '';
  formData.sort = 0;
  formData.input_type = 'text';
  formData.val = '';
  formData.ext = [];
  formData.pid = 0;
  formData.remark = '';
}

// 新增选项
const addChoiceList = () => {
  if (formData.ext.length >= 10) {
    ElMessage.warning('选项不能超过10个');
    return;
  }
  formData.ext.push({ name: '', id: formData.ext.length + 1 });
  console.log(formData.ext)
}

// 删除选项
const hanldeDelChoice = (index: number) => {
  formData.ext.splice(index, 1);
}

// 刷新缓存
const hanldeRefreshAll = () => {
  getRefreshAll({}).then(res => {
    handleQuery();
  })
}

onMounted(() => {
  handleQuery(); // 初始化用户列表数据
});
</script>

<template>
  <div class="app-container">
    <el-row :gutter="20">

      <el-col :lg="24" :xs="24">
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">
            <el-form-item label="code" prop="s_code">
              <el-input v-model="queryParams.s_code" placeholder="请输入唯一标识" clearable style="width: 200px"
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="名称" prop="s_name">
              <el-input v-model="queryParams.s_name" placeholder="请输入名称" clearable style="width: 200px"
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery"><i-ep-search />搜索</el-button>
              <el-button @click="resetQuery"><i-ep-refresh />重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="never">
          <template #header>
            <div class="flex justify-between">
              <div>
                <el-button @click="openDialog()" type="primary"><i-ep-plus />新增</el-button>
                <el-button @click="hanldeRefreshAll" type="primary"><i-ep-refresh />刷新缓存</el-button>
              </div>
            </div>
          </template>
          <el-table v-loading="loading" :data="userList">
            <el-table-column label="ID" align="center" prop="id" width="50" />
            <el-table-column label="排序" align="center" prop="sort" width="100" />
            <el-table-column label="标题" align="center" prop="name" />
            <el-table-column label="code" align="center" prop="code" />
            <el-table-column label="数据类型" align="center" prop="input_type" width="120" />
            <el-table-column label="选择" align="center" width="150">
              <template #default="scope">
                <div v-for="(item) in scope.row.ext" :key="item.id">{{ item.id }}--{{ item.name }}</div>
              </template>
            </el-table-column>
            <el-table-column label="选中值" align="center" prop="val" width="150">
              <template #default="scope">
                <template v-if="scope.row.input_type == 'text' || scope.row.input_type == 'textarea'">
                  <div>{{ scope.row.val }}</div>
                </template>
                <template v-else>
                  <div v-for="(item) in scope.row.ext" :key="item.id">
                    <div v-if="item.id == scope.row.val">{{ item.name }}</div>
                  </div>
                </template>
              </template>
            </el-table-column>
            <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
            <el-table-column label="操作" fixed="right" align="center" width="280">
              <template #default="scope">
                <el-button type="primary" link size="small"
                  @click.stop="openDialog(scope.row.id, scope.row)">修改</el-button>
                <el-button type="primary" link size="small" @click.stop="handleDelete(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.page"
            v-model:limit="queryParams.ps" @pagination="handleQuery" />
        </el-card>
      </el-col>
    </el-row>

    <el-dialog v-model="dialog.visible" :title="dialog.title" destroy-on-close append-to-body width="60%"
      @close="closeDialog">
      <el-form ref="menuFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="formData.sort" placeholder="请输入唯一标识" />
        </el-form-item>
        <el-form-item label="唯一标识" prop="code">
          <el-input v-model="formData.code" placeholder="请输入唯一标识" :disabled="isEdit" />
        </el-form-item>

        <el-form-item label="类型" prop="input_type">
          <el-radio-group v-model="formData.input_type" @change="hanldeChangeRadio" :disabled="isEdit">
            <el-radio value="text">输入框</el-radio>
            <el-radio value="radio">单选</el-radio>
            <el-radio value="checkbox">多选</el-radio>
            <el-radio value="editor">富文本</el-radio>
          </el-radio-group>
        </el-form-item>

        <template v-if="formData.input_type == 'checkbox' || formData.input_type == 'radio'">
          <el-form-item :label="String.fromCharCode(64 + (index + 1))" v-for="(item, index) in formData.ext"
            :key="item.id">
            <div class="flex" style="width: 100%;">
              <el-input clearable class="mr-10 flex-1" v-model="item.name" placeholder="请输入选项" />
              <div style="width: 100px;">
                <el-button @click="hanldeDelChoice(index)" v-if="index > 1" type="danger">删除选项</el-button>
              </div>
            </div>
          </el-form-item>
          <el-form-item>
            <div class="flex">
              <el-button type="primary" @click="addChoiceList">新增选项</el-button>
              <span>（最多添加10个选项）</span>
            </div>
          </el-form-item>
        </template>

        <el-form-item label="选中值" prop="val">
          <el-checkbox-group v-if="formData.input_type == 'checkbox'" v-model="formData.checkbox" size="small">
            <el-checkbox v-for="(item) in formData.ext" :value="item.id" border :label="item.name" :key="item.id" />
          </el-checkbox-group>

          <el-radio-group v-else-if="formData.input_type == 'radio'" v-model="formData.val">
            <el-radio v-for="(item) in formData.ext" :value="item.id" :key="item.id">
              {{ item.name }}
            </el-radio>
          </el-radio-group>
          <el-input v-else-if="formData.input_type == 'text'" v-model="formData.val" placeholder="请输入选中值" />
          <div v-else-if="formData.input_type == 'editor'" style="height: 490px; border: 1px solid #EBEEFF;">
            <editor v-model="formData.val" style="height:400px; width: 100%;" />
          </div>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" placeholder="请输入备注" />
        </el-form-item>

      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
